package com.atguigu.daijia.driver.service.impl;

import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.driver.util.CloudApiOperator;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.qcloud.cos.model.ObjectMetadata;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {
    @Resource
    private CloudApiOperator cloudApiOperator;

    /**
     * 文件上传
     */
    @Override
    public CosUploadVo upload(MultipartFile file, String path) {
        //元数据信息
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.getSize());
        meta.setContentEncoding("UTF-8");
        meta.setContentType(file.getContentType());

        //向存储桶中保存文件
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //文件后缀名
        String uploadPath = "/driver/" + path + "/" + UUID.randomUUID().toString().replaceAll("-", "") + fileType;
        try {
            cloudApiOperator.upload(uploadPath, file.getInputStream(), meta);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        CosUploadVo vo = new CosUploadVo();
        vo.setUrl(uploadPath);
        vo.setShowUrl(getImageUrl(uploadPath));
        return vo;
    }

    /**
     * 获取临时签名url
     */
    @Override
    public String getImageUrl(String path) {
        if (StringUtils.isBlank(path)) {
            return "";
        }
        return cloudApiOperator.getImageUrl(path);
    }
}
